package com.rising.nio;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2020/8/23 14:47
 */
public class MergeList {
    public static void main(String[] args) {
        String str = "";
        /*str = "1->3->4->7->9,4->5->8";
        System.out.println(mergeList(str));
        str = "4->5->8,1->3->4->7->9";
        System.out.println(mergeList(str));*/
        /*str = "4->5->8,1->3->4->7->9,0";
        System.out.println(mergeList(str));*/
        str = "4->5->8,1->3->4->7->9,0,2->3->20->30->40,21->22->23";
        System.out.println("输入：" + str);
        System.out.println("输出：" + mergeList(str));
    }

    private static String mergeList(String lists) {
        String[] split = lists.split(",");
        if (split.length < 2) {
            return lists;
        }

        String[] mergeList  = mergeListFor2(split[0].split("->"), split[1].split("->"));
        for (int i = 2; i < split.length; i++) {
            mergeList = mergeListFor2(mergeList, split[i].split("->"));
        }
        StringBuilder stringBuilder = new StringBuilder();
        for (String s : mergeList) {
            stringBuilder.append(s).append("->");
        }
        String rtnString = stringBuilder.toString();
        return rtnString.substring(0, rtnString.lastIndexOf("->"));
    }


    private static String[] mergeListFor2(String[] firstList, String[] secondList) {
        String[] mergeList = new String[firstList.length + secondList.length];

        String[] temp = null;
        if (Integer.parseInt(firstList[0]) < Integer.parseInt(secondList[0])) {
            temp = secondList;
            secondList = firstList;
            firstList = temp;
        }

        String fstart = firstList[0];
        int i = 0;
        int k = 0;
        for (int j = 0; j < secondList.length; j++) {
            if (Integer.parseInt(fstart) >= Integer.parseInt(secondList[j])) {
                mergeList[i] = secondList[j];
                i++;
                continue;
            }
            for (; k < firstList.length; k++) {
                if (Integer.parseInt(firstList[k]) <= Integer.parseInt(secondList[j])) {
                    mergeList[i] = firstList[k];
                    i++;
                } else {
                    fstart = firstList[k];
                    break;
                }
            }
            mergeList[i] = secondList[j];
            i++;
        }
        for (; k < firstList.length; k++) {
            mergeList[i] = firstList[k];
            i++;
        }
        return mergeList;
    }
}


